
package botlab.gui.actionlistener;

import botlab.Game;
import botlab.GameManager;
import botlab.command.BaseCommand;
import botlab.compiler.CommandCreator;
import botlab.gui.GUI;
import botlab.gui.Notifier;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.Callable;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Quentin
 */
public class StartActionListener implements ActionListener
{
    private GUI gui;
    
    public StartActionListener(GUI gui)
    {
        this.gui = gui;
    }

    public void actionPerformed(ActionEvent e)
    {
        final Game game = GameManager.getInstance().getGame();
        BaseCommand bc=null;
        
        // clear old errors if any
        gui.getErrorsArea().setText("");
        
        //compilation
        try
        {
            bc = CommandCreator.getInstance().newBaseCommand(
                                    gui.getEditorPane().getText());
        } catch (Exception ex){}

        // if no errors
        if(bc!=null)
        {
            final BaseCommand bcf = bc;

            // start level
            game.enqueue(new Callable<Void>()
            {
                public Void call()
                {
                        try
                        {
                            game.startLevel(bcf);
                        } 
                        catch (Exception ex)
                        {
                            Logger.getLogger(GUI.class.getName()).log(Level.SEVERE,
                                    null, ex);
                        }
                        return null;
                }
            });
            
            // switch to render panel
            gui.setMode(GUI.RENDER);
            Notifier.getInstance().enterState("render");
        }
        else
            Notifier.getInstance().enterState("errors");
    }
}
